package org.innovasix.educational.javap.util;

import org.innovasix.educational.javap.exception.InvalidArgumentException;

public class HexString {
	
	public static byte[] toByteArray(String stringWithHexCharacters) {
		
		if((stringWithHexCharacters.length() % 2 != 0))
			throw new InvalidArgumentException("stringWithHexCharacters.length is not even");
		
		byte[] byteArray = new byte[stringWithHexCharacters.length() / 2]; 
		
		char[] inputCharArray = stringWithHexCharacters.toCharArray();
		
		for(int i = 0, j = 0; i < inputCharArray.length; i = i + 2, j++){
			
			byte firstCharByteValue = (byte) Character.digit(inputCharArray[i], 16);
			byte secondCharByteValue = (byte) Character.digit(inputCharArray[i+1], 16);
			
			if(firstCharByteValue == -1 || secondCharByteValue == -1)
				throw new InvalidArgumentException("Either " + inputCharArray[i] + " or " + inputCharArray[i+1] + " is not a valid hex char.");
			byteArray[j] = (byte) ((firstCharByteValue << 4 ) + secondCharByteValue);
		}
		
		return byteArray;
	} 

}
